<template>
  <CustomerLayout>
    <div class="store-detail-container">
      <!-- 1. 顶部区域（商家概览） -->
      <div class="store-header">
        <div class="store-cover" :style="{ backgroundImage: `url(${formatImageUrl(storeInfo.coverImage)})` }">
          <div class="store-info-overlay">
            <div class="store-logo">
              <img :src="formatImageUrl(storeInfo.logo) || '/placeholder-logo.png'" alt="店铺logo" />
            </div>
          <div class="store-basic-info">
            <h1 class="store-name">{{ storeInfo.name }}</h1>
            <div class="store-stats">
              <span class="rating">
                <star-rating :score="storeInfo.rating" :show-score="true" />
              </span>
              <span class="divider">|</span>
              <span class="monthly-sales">月售 {{ storeInfo.monthSales }}+</span>
              <span class="divider">|</span>
              <span class="delivery-time">{{ storeInfo.deliveryTime }}分钟</span>
              <span class="divider">|</span>
              <span class="min-order">起送¥{{ storeInfo.minOrder }}</span>
            </div>
            <div class="store-tags">
              <el-tag v-for="tag in storeInfo.tags" :key="tag" size="small" effect="plain">
                {{ tag }}
              </el-tag>
              <el-tag v-if="storeInfo.promotion" type="danger" size="small" effect="plain">
                {{ storeInfo.promotion }}
              </el-tag>
            </div>
          </div>
          <div class="store-actions">
            <el-button
              :type="isFavorite ? 'danger' : 'default'"
              :icon="isFavorite ? StarFilled : Star"
              circle
              @click="toggleFavorite"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 2. 内容导航区 -->
    <div class="nav-container" :class="{ 'sticky': isNavSticky }">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="点菜" name="menu"></el-tab-pane>
        <!-- <el-tab-pane label="评价" name="reviews"></el-tab-pane> -->
        <el-tab-pane label="商家" name="info"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 3. 点菜区域（主要内容） -->
    <div v-show="activeTab === 'menu'" class="menu-container">
      <div class="menu-layout">
        <!-- 左侧分类导航 -->
        <div class="category-nav" :class="{ collapsed: isSidebarCollapsed }">
          <div class="category-nav-header">
            <span v-show="!isSidebarCollapsed" class="nav-title">商品分类</span>
            <el-button 
              link 
              :icon="isSidebarCollapsed ? ArrowRight : ArrowLeft"
              @click="toggleSidebar"
              size="small"
              class="toggle-btn"
            />
          </div>
          <ul>
            <!-- 特色餐品导航 -->
            <li
              v-if="featuredFoods.length > 0"
              :class="{ 'active': currentCategory === 'featured' }"
              @click="scrollToCategory('featured')"
              :title="isSidebarCollapsed ? '特色餐品' : ''"
            >
              <el-icon class="category-icon"><StarFilled /></el-icon>
              <span class="category-text">特色餐品</span>
            </li>
            
            <!-- 普通分类导航 -->
            <li
              v-for="category in categories"
              :key="category.id"
              :class="{ 'active': currentCategory === category.id }"
              @click="scrollToCategory(category.id)"
              :title="isSidebarCollapsed ? category.name : ''"
            >
              <el-icon class="category-icon"><component :is="getCategoryIcon(category.name)" /></el-icon>
              <span class="category-text">{{ category.name }}</span>
            </li>
          </ul>
        </div>

        <!-- 右侧菜品列表 -->
        <div class="food-list" ref="foodListRef">
          <!-- 特色餐品区域 -->
          <div 
            v-if="featuredFoods.length > 0"
            class="category-section featured-section"
            id="category-featured"
          >
            <h3 class="category-title featured-title">
              <el-icon><StarFilled /></el-icon>
              特色餐品
            </h3>
            <div class="foods-grid">
              <food-card 
                v-for="food in featuredFoods" 
                :key="food.id"
                :food="food"
                @click="openFoodDetail"
                @add="addToCart(food)"
              />
            </div>
          </div>
          
          <!-- 普通分类区域 -->
          <div
            v-for="category in categories"
            :key="category.id"
            :id="`category-${category.id}`"
            class="category-section"
          >
            <h3 class="category-title">{{ category.name }}</h3>
            <div class="foods-grid">
              <food-card 
                v-for="food in getFoodsByCategory(category.id)" 
                :key="food.id"
                :food="food"
                @click="openFoodDetail"
                @add="addToCart(food)"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 4. 评价区域
    <div v-show="activeTab === 'reviews'" class="reviews-container">
      <div class="reviews-summary">
        <div class="overall-rating">
          <h3>{{ storeInfo.rating }}</h3>
          <star-rating :score="storeInfo.rating" :show-score="false" />
          <p>综合评分</p>
        </div>
        <div class="rating-filters">
          <el-radio-group v-model="reviewFilter" @change="loadReviews">
            <el-radio-button label="all">全部({{ reviewCounts.all }})</el-radio-button>
            <el-radio-button label="good">好评({{ reviewCounts.good }})</el-radio-button>
            <el-radio-button label="medium">中评({{ reviewCounts.medium }})</el-radio-button>
            <el-radio-button label="bad">差评({{ reviewCounts.bad }})</el-radio-button>
            <el-radio-button label="withPhotos">有图({{ reviewCounts.withPhotos }})</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <div class="reviews-list">
        <review-item 
          v-for="review in reviews" 
          :key="review.id" 
          :review="review"
          @preview-image="previewImage"
        />

        <div class="pagination-container">
          <el-pagination
            layout="prev, pager, next"
            :total="reviewTotal"
            :current-page="reviewPage"
            :page-size="reviewPageSize"
            @current-change="handleReviewPageChange"
          />
        </div>
      </div>
    </div> -->

    <!-- 5. 商家详情区域 -->
    <div v-show="activeTab === 'info'" class="store-detail-info">
      <el-descriptions title="商家信息" :column="1" border>
        <el-descriptions-item label="商家名称">{{ storeInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="商家介绍">{{ storeInfo.description }}</el-descriptions-item>
        <el-descriptions-item label="营业时间">{{ storeInfo.businessHours }}</el-descriptions-item>
        <el-descriptions-item label="商家地址">{{ storeInfo.address }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ storeInfo.phone }}</el-descriptions-item>
        <el-descriptions-item label="商家分类">{{ storeInfo.type }}</el-descriptions-item>
        <el-descriptions-item label="配送时间">{{ storeInfo.deliveryTime }}分钟</el-descriptions-item>
        <el-descriptions-item label="起送金额">¥{{ storeInfo.minOrder }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="store-map" v-if="storeInfo.address">
        <!-- 这里可以集成地图组件，显示商家位置 -->
        <p>商家地图位置将在这里显示</p>
      </div>
    </div>

    <!-- 6. 底部购物车区域 -->
    <div class="cart-bar">
      <div class="cart-info" @click="toggleCartPanel">
        <div class="cart-icon" :class="{ 'has-items': cartItems.length > 0 }">
          <el-icon size="24"><ShoppingCartFull /></el-icon>
          <span v-if="cartItems.length > 0" class="cart-count">{{ getTotalItems() }}</span>
        </div>
        <div class="cart-price">
          <template v-if="getTotalPrice() > 0">
            <span class="total-price">¥{{ getTotalPrice() }}</span>
            <span v-if="getTotalPrice() < storeInfo.minOrder" class="min-price-tip">
              还差¥{{ (storeInfo.minOrder - getTotalPrice()).toFixed(2) }}起送
            </span>
          </template>
          <template v-else>
            <span class="empty-cart">未选购商品</span>
          </template>
        </div>
      </div>
      <div class="checkout-btn">
        <el-button
          type="primary"
          :disabled="getTotalPrice() < storeInfo.minOrder"
          @click="goToCheckout"
        >
          去结算
        </el-button>
      </div>
    </div>

    <!-- 购物车面板 -->
    <el-drawer
      v-model="cartPanelVisible"
      title="我的购物车"
      direction="btt"
      size="50%"
    >
      <div class="cart-panel-content">
        <div v-if="cartItems.length === 0" class="empty-cart-tip">
          <el-icon size="48"><ShoppingCartFull /></el-icon>
          <p>购物车空空如也，去选购商品吧~</p>
        </div>
        <div v-else>
          <div class="cart-item-list">
            <div v-for="item in cartItems" :key="item.id" class="cart-item">
              <div class="item-info">
                <img :src="formatImageUrl(item.foodImage)" :alt="item.foodName" class="item-image" />
                <div class="item-details">
                  <h4>{{ item.foodName }}</h4>
                  <p v-if="item.attributes && item.attributes.length">
                    <span v-for="(attr, index) in item.attributes" :key="index">
                      {{ attr.name }}: {{ attr.options.join(', ') }}
                      <span v-if="index < item.attributes.length - 1">; </span>
                    </span>
                  </p>
                </div>
              </div>
              <div class="item-price-actions">
                <span class="item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
                <div class="item-quantity">
                  <el-button
                    type="danger"
                    :icon="Minus"
                    circle
                    size="small"
                    @click="updateCartItemQuantity(item, -1)"
                  />
                  <span class="quantity">{{ item.quantity }}</span>
                  <el-button
                    type="primary"
                    :icon="Plus"
                    circle
                    size="small"
                    @click="updateCartItemQuantity(item, 1)"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="cart-summary">
            <div class="summary-item">
              <span>商品金额</span>
              <span>¥{{ getTotalPrice().toFixed(2) }}</span>
            </div>
            <div class="summary-item">
              <span>配送费</span>
              <span>¥{{ deliveryFee.toFixed(2) }}</span>
            </div>
            <div class="summary-item">
              <span>包装费</span>
              <span>¥{{ packageFee.toFixed(2) }}</span>
            </div>
            <div class="summary-total">
              <span>合计</span>
              <span>¥{{ (getTotalPrice() + deliveryFee + packageFee).toFixed(2) }}</span>
            </div>
          </div>
          <div class="cart-actions">
            <el-button @click="clearCart">清空购物车</el-button>
            <el-button
              type="primary"
              :disabled="getTotalPrice() < storeInfo.minOrder"
              @click="goToCheckout"
            >
              去结算
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 7. 商品详情弹窗 -->
    <el-dialog
      v-model="foodDetailVisible"
      :title="selectedFood?.name || '商品详情'"
      width="70%"
    >
      <div v-if="selectedFood" class="food-detail-content">
        <div class="food-detail-left">
          <div class="food-detail-image">
            <img :src="formatImageUrl(selectedFood.image)" :alt="selectedFood.name" />
          </div>
        </div>
        <div class="food-detail-right">
          <div class="food-detail-header">
            <h2>{{ selectedFood.name }}</h2>
            <el-button
              :type="isFoodFavorite ? 'danger' : 'default'"
              :icon="isFoodFavorite ? StarFilled : Star"
              circle
              @click="toggleFoodFavorite"
              title="收藏商品"
              class="favorite-btn"
            />
          </div>
          <p class="food-detail-desc">{{ selectedFood.description }}</p>
          <div class="food-detail-price">
            <span class="current-price">¥{{ selectedFood.price }}</span>
            <span v-if="selectedFood.originalPrice" class="original-price">
              ¥{{ selectedFood.originalPrice }}
            </span>
          </div>
          <div class="food-detail-stats">
            <span class="food-rating">
              <star-rating :score="selectedFood.rating" :show-score="true" />
            </span>
            <span class="food-sales">月售{{ selectedFood.monthlySales }}+</span>
          </div>

          <!-- 商品属性选择 -->
          <div v-if="selectedFood.attributes && selectedFood.attributes.length" class="food-attributes">
            <div
              v-for="attr in selectedFood.attributes"
              :key="attr.name"
              class="attr-group"
            >
              <h4>{{ attr.name }}
                <span v-if="attr.required" class="required">*</span>
                <span v-else class="optional">(可选)</span>
              </h4>
              <div class="attr-options">
                <template v-if="attr.multiSelect">
                  <el-checkbox-group v-model="selectedAttributes[attr.name]">
                    <el-checkbox
                      v-for="option in attr.options"
                      :key="option.name"
                      :label="option.name"
                    >
                      {{ option.name }}
                      <span v-if="option.price > 0" class="option-price">+¥{{ option.price }}</span>
                    </el-checkbox>
                  </el-checkbox-group>
                </template>
                <template v-else>
                  <el-radio-group v-model="selectedAttributes[attr.name]">
                    <el-radio
                      v-for="option in attr.options"
                      :key="option.name"
                      :label="option.name"
                    >
                      {{ option.name }}
                      <span v-if="option.price > 0" class="option-price">+¥{{ option.price }}</span>
                    </el-radio>
                  </el-radio-group>
                </template>
              </div>
            </div>
          </div>

          <!-- 数量选择 -->
          <div class="quantity-selector">
            <span>数量</span>
            <div class="quantity-controls">
              <el-button
                type="danger"
                :icon="Minus"
                circle
                size="small"
                :disabled="foodQuantity <= 1"
                @click="foodQuantity--"
              />
              <span class="quantity">{{ foodQuantity }}</span>
              <el-button
                type="primary"
                :icon="Plus"
                circle
                size="small"
                @click="foodQuantity++"
              />
            </div>
          </div>

          <!-- 商品评价区域 -->
          <div class="food-reviews-section">
            <h3>商品评价 ({{ foodReviews.length }})</h3>
            <div v-if="foodReviews.length > 0" class="food-reviews-list">
              <div 
                v-for="review in foodReviews" 
                :key="review.id" 
                class="food-review-item"
              >
                <div class="review-header">
                  <img :src="review.userAvatar || '/default-avatar.png'" class="user-avatar" />
                  <div class="review-info">
                    <span class="user-name">{{ review.userName }}</span>
                    <star-rating :score="review.rating" :show-score="false" size="small" />
                  </div>
                  <span class="review-time">{{ formatTime(review.createTime) }}</span>
                </div>
                <p class="review-content">{{ review.content }}</p>
                <div v-if="review.images && review.images.length" class="review-images">
                  <img 
                    v-for="(image, index) in review.images" 
                    :key="index"
                    :src="formatImageUrl(image)" 
                    @click="previewImage(review.images, index)"
                    class="review-image"
                  />
                </div>
              </div>
            </div>
            <div v-else class="no-reviews">
              <p>暂无评价</p>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="foodDetailVisible = false">取消</el-button>
          <el-button type="primary" @click="addSelectedFoodToCart">加入购物车</el-button>
        </div>
      </template>
    </el-dialog>
    </div>
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  ArrowLeft, 
  ArrowRight, 
  Plus, 
  Minus, 
  ShoppingCartFull,
  StarFilled,
  Star,
  Food as FoodIcon,
  CoffeeCup,
  IceCream,
  Bowl,
  Box,
  Goods
} from '@element-plus/icons-vue';
import CustomerLayout from "@/components/customer/CustomerLayout.vue";
import FoodCard from "@/components/customer/FoodCard.vue";
import ReviewItem from "@/components/customer/ReviewItem.vue";
import StarRating from "@/components/common/StarRating.vue";
import { 
  storeApi, 
  foodApi, 
  favoriteApi,
  historyApi,
  cartApi 
} from '@/api/customer';
import { 
  Store, 
  Food, 
  Review, 
  CartItem, 
  FoodAttribute,
  SelectedAttribute
} from '@/types/customer';
import { formatImageUrl } from '@/utils/image';

const route = useRoute();
const router = useRouter();
const storeId = computed(() => route.params.id as string);

// 店铺信息
const storeInfo = ref<Store>({} as Store);
const isFavorite = ref(false);
const categories = ref<any[]>([]);
const foodsByCategory = ref<Record<number, Food[]>>({});
const featuredFoods = ref<Food[]>([]); // 特色餐品

// 导航相关
const activeTab = ref('menu');
const isNavSticky = ref(false);
const currentCategory = ref<number | string | null>(null);
const foodListRef = ref<HTMLElement | null>(null);
const isSidebarCollapsed = ref(false);

// 评价相关
const reviews = ref<Review[]>([]);
const reviewFilter = ref('all');
const reviewPage = ref(1);
const reviewPageSize = ref(10);
const reviewTotal = ref(0);
const reviewCounts = reactive({
  all: 0,
  good: 0,
  medium: 0,
  bad: 0,
  withPhotos: 0
});

// 购物车相关
const cartItems = ref<CartItem[]>([]);
const cartPanelVisible = ref(false);
const deliveryFee = ref(0);
const packageFee = ref(0);

// 商品详情相关
const foodDetailVisible = ref(false);
const selectedFood = ref<Food | null>(null);
const foodQuantity = ref(1);
const selectedAttributes = ref<Record<string, string | string[]>>({});
const isFoodFavorite = ref(false);
const foodReviews = ref<Review[]>([]);

// 初始化数据
onMounted(() => {
  // 添加滚动监听
  window.addEventListener('scroll', handleScroll);
  
  // 读取侧边栏状态偏好
  const savedState = localStorage.getItem('sidebarCollapsed');
  if (savedState !== null) {
    isSidebarCollapsed.value = savedState === 'true';
  }
  
  // 使用异步函数包装以避免生命周期钩子问题
  const initializeData = async () => {
    try {
      // 加载数据
      await loadStoreInfo(); // 先加载店铺信息
      await loadCategories(); // 再加载分类（依赖店铺信息）
      await loadCartItems(); // 最后加载购物车
      
      // 记录浏览历史
      try {
        await historyApi.addHistory(parseInt(storeId.value));
      } catch (error) {
        console.error('添加浏览历史失败:', error);
        // 浏览历史添加失败不影响正常使用，只需记录错误
      }
      
      // 检查是否需要打开特定商品详情（从历史记录页面跳转）
      const foodId = route.query.foodId;
      if (foodId) {
        // 等待分类和商品数据加载完成后再查找并打开商品详情
        await nextTick();
        const allFoods = Object.values(foodsByCategory.value).flat();
        const targetFood = allFoods.find(food => food.id.toString() === foodId);
        if (targetFood) {
          await openFoodDetail(targetFood);
        }
      }
    } catch (error) {
      console.error('页面初始化失败:', error);
    }
  };
  
  // 调用异步初始化函数
  initializeData();
});

onBeforeUnmount(() => {
  // 移除滚动监听
  window.removeEventListener('scroll', handleScroll);
});

// 处理滚动事件
const handleScroll = () => {
  // 导航栏吸顶效果
  const navContainer = document.querySelector('.nav-container');
  if (navContainer) {
    const rect = navContainer.getBoundingClientRect();
    isNavSticky.value = rect.top <= 0;
  }
  
  // 菜单滚动时更新当前分类
  if (activeTab.value === 'menu' && foodListRef.value) {
    const categoryElements = foodListRef.value.querySelectorAll('.category-section');
    for (let i = 0; i < categoryElements.length; i++) {
      const element = categoryElements[i];
      const rect = element.getBoundingClientRect();
      if (rect.top <= 100 && rect.bottom > 100) {
        const id = element.id.replace('category-', '');
        if (id === 'featured') {
          currentCategory.value = 'featured';
        } else {
          currentCategory.value = parseInt(id);
        }
        break;
      }
    }
  }
};

// 加载店铺信息
const loadStoreInfo = async () => {
  try {
    const response = await storeApi.getStoreDetail(storeId.value);
    console.log('API响应完整数据:', response);
    console.log('店铺数据:', response.data);
    
    // 处理API响应数据结构
    let storeData = response.data;
    // 如果response.data是包装了一层的格式（如{status, message, data}），提取实际数据
    if (storeData && storeData.data && typeof storeData.data === 'object') {
      storeData = storeData.data;
    }
    
    console.log('处理后的店铺数据:', storeData);
    console.log('店铺状态:', storeData?.status);
    
    // 字段映射和数据处理
    if (storeData) {
      storeInfo.value = {
        ...storeData,
        // 确保关键字段正确映射，使用API返回的字段名
        monthSales: storeData.monthlySales || storeData.monthSales || 0,
        deliveryTime: storeData.averageDeliveryTime || storeData.deliveryTime || 30,
        minOrder: storeData.minOrderAmount || storeData.minOrder || 0,
        // 使用logo字段作为封面图
        coverImage: storeData.logo || storeData.coverImage || '',
        tags: storeData.tags || [],
        promotion: storeData.promotion || null
      };
      
      console.log('最终店铺信息:', storeInfo.value);
    }
    
    // 参考微信小程序的实现，检查店铺营业状态
    if (storeInfo.value.status && storeInfo.value.status !== 'OPEN') {
      console.warn('店铺状态检查失败:', storeInfo.value.status);
      ElMessage.error('店铺未营业');
      setTimeout(() => {
        router.back();
      }, 1500);
      return;
    }
    
    // 检查是否已收藏
    try {
      const favoriteStatus = await favoriteApi.checkStoreFavorite(parseInt(storeId.value));
      console.log('店铺收藏检查 - 完整响应:', favoriteStatus);
      console.log('店铺收藏检查 - data值:', favoriteStatus.data);
      
      // 处理API响应的嵌套结构
      const actualData = favoriteStatus.data.data !== undefined ? favoriteStatus.data.data : favoriteStatus.data;
      console.log('店铺收藏检查 - 实际data值:', actualData);
      
      // 根据微信小程序的实现，检查返回值是否等于1
      isFavorite.value = actualData === 1 || actualData === true;
      console.log('店铺收藏检查 - 判断结果:', isFavorite.value);
    } catch (error) {
      console.error('检查收藏状态失败:', error);
      isFavorite.value = false;
    }
    
    // 设置配送费和包装费（示例值，实际应从API获取）
    deliveryFee.value = (storeInfo.value as any).deliveryFee || 5;
    packageFee.value = (storeInfo.value as any).packageFee || 1;
  } catch (error) {
    ElMessage.error('获取店铺信息失败');
    console.error(error);
  }
};

// 加载分类和食品
const loadCategories = async () => {
  try {
    // 从店铺信息中获取分类和特色餐品
    const storeData = storeInfo.value as any;
    
    // 处理特色餐品
    if (storeData.featuredFoods && storeData.featuredFoods.length > 0) {
      featuredFoods.value = storeData.featuredFoods.map((food: any) => ({
        ...food,
        monthlySales: food.sales || 0,
        rating: food.rating || 4.5,
        originalPrice: food.originalPrice || null,
        image: formatImageUrl(food.image)
      }));
      console.log('处理后的特色餐品:', featuredFoods.value);
    }
    
    // 处理分类
    if (storeData.categories && storeData.categories.length > 0) {
      categories.value = storeData.categories.sort((a: any, b: any) => (a.sort || 0) - (b.sort || 0));
      console.log('从店铺信息中获取的分类:', categories.value);
    } else {
      // 如果店铺信息中没有分类，则通过API获取
      const categoriesData = await storeApi.getStoreCategories(storeId.value);
      categories.value = categoriesData.data || [];
      console.log('通过API获取的分类:', categories.value);
    }
    
    // 设置默认选中分类
    if (featuredFoods.value.length > 0) {
      currentCategory.value = 'featured';
    } else if (categories.value.length > 0) {
      currentCategory.value = categories.value[0].id;
    }
    
    // 为所有分类加载食品数据
    if (categories.value.length > 0) {
      await Promise.all(
        categories.value.map(async (category) => {
          try {
            const foods = await foodApi.getStoreFoods(storeId.value, { 
              categoryId: category.id.toString() 
            });
            console.log(`分类${category.id}的食品数据:`, foods);
            
            // 处理不同的响应格式
            if (foods && foods.data) {
              const responseData = foods.data as any;
              let foodsArray: any[] = [];
              
              if (Array.isArray(responseData)) {
                foodsArray = responseData;
              } else if (responseData.content) {
                // 分页格式
                foodsArray = responseData.content;
              } else if (responseData.data) {
                // 嵌套数据格式
                foodsArray = responseData.data;
              }
              
              // 处理食品数据
              foodsByCategory.value[category.id] = foodsArray.map((food: any) => ({
                ...food,
                monthlySales: food.sales || food.monthlySales || 0,
                rating: food.rating || 4.5,
                originalPrice: food.originalPrice || null,
                image: formatImageUrl(food.image)
              }));
            } else {
              foodsByCategory.value[category.id] = [];
            }
          } catch (error) {
            console.error(`获取分类${category.id}商品失败:`, error);
            foodsByCategory.value[category.id] = [];
          }
        })
      );
      
      console.log('所有分类的食品数据:', foodsByCategory.value);
    }
  } catch (error) {
    ElMessage.error('获取分类信息失败');
    console.error(error);
  }
};

// 加载评价
const loadReviews = async () => {
  try {
    const params = {
      page: reviewPage.value,
      pageSize: reviewPageSize.value,
      filter: reviewFilter.value === 'all' ? undefined : reviewFilter.value
    };
    
    const reviewsData = await storeApi.getStoreReviews(storeId.value, params);
    if (reviewsData && reviewsData.data) {
      reviews.value = reviewsData.data.data || [];
      reviewTotal.value = reviewsData.data.total || 0;
      
      // 获取各类评价数量（示例实现，实际应从API获取）
      reviewCounts.all = reviewTotal.value;
      reviewCounts.good = Math.floor(reviewTotal.value * 0.7);
      reviewCounts.medium = Math.floor(reviewTotal.value * 0.2);
      reviewCounts.bad = Math.floor(reviewTotal.value * 0.1);
      reviewCounts.withPhotos = Math.floor(reviewTotal.value * 0.3);
    }
  } catch (error) {
    ElMessage.error('获取评价信息失败');
    console.error(error);
  }
};

// 处理评价分页
const handleReviewPageChange = (page: number) => {
  reviewPage.value = page;
  loadReviews();
};

// 加载购物车
const loadCartItems = async () => {
  try {
    // 参考微信小程序的实现，获取指定店铺的购物车
    const data = await cartApi.getStoreCart(parseInt(storeId.value));
    console.log('购物车API响应:', data);
    
    if (data && data.data) {
      // 处理API响应数据结构
      let cartData = data.data;
      // 如果data.data是包装了一层的格式，提取实际数据
      if (cartData.data && typeof cartData.data === 'object') {
        cartData = cartData.data;
      }
      
      console.log('处理后的购物车数据:', cartData);
      
      // 直接使用API返回的items数组
      cartItems.value = cartData.items || [];
      
      // 确保每个商品都有正确的图片路径和字段映射
      cartItems.value = cartItems.value.map(item => ({
        ...item,
        // 确保字段名称一致，处理图片URL
        foodImage: formatImageUrl(item.foodImage),
        // 确保有必要的字段
        price: item.price || 0,
        quantity: item.quantity || 1,
        // 确保有正确的购物车项ID，尝试不同的可能字段名
        id: item.id || (item as any).cartItemId || (item as any).itemId || (item as any).cartId
      }));
      
      console.log('最终购物车项目:', cartItems.value);
      console.log('购物车项目ID检查:', cartItems.value.map(item => ({ 
        foodName: item.foodName, 
        id: item.id,
        cartItemId: (item as any).cartItemId,
        itemId: (item as any).itemId,
        cartId: (item as any).cartId,
        originalItem: item
      })));
    } else {
      cartItems.value = [];
    }
  } catch (error) {
    console.error('获取购物车信息失败:', error);
    cartItems.value = [];
  }
};

// 切换收藏状态
const toggleFavorite = async () => {
  try {
    if (isFavorite.value) {
      await favoriteApi.removeFavoriteStore(parseInt(storeId.value));
      ElMessage.success('已取消收藏');
    } else {
      await favoriteApi.addFavoriteStore(parseInt(storeId.value));
      ElMessage.success('已收藏');
    }
    isFavorite.value = !isFavorite.value;
  } catch (error) {
    ElMessage.error('操作失败');
    console.error(error);
  }
};

// 切换侧边栏状态
const toggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value;
  // 保存用户偏好到本地存储
  localStorage.setItem('sidebarCollapsed', isSidebarCollapsed.value.toString());
};

// 获取分类图标
const getCategoryIcon = (categoryName: string) => {
  const iconMap: Record<string, any> = {
    '热销': StarFilled,
    '主食': FoodIcon,
    '饮品': CoffeeCup,
    '小食': IceCream,
    '甜品': IceCream,
    '套餐': Box,
    '汤品': Bowl,
    '凉菜': IceCream
  };
  return iconMap[categoryName] || Goods;
};

// 检查商品是否已收藏
const checkFoodFavorite = async (foodId: string) => {
  try {
    const response = await favoriteApi.checkFoodFavorite(parseInt(foodId));
    console.log('食品收藏检查 - 完整响应:', response);
    console.log('食品收藏检查 - data值:', response.data);
    
    // 处理API响应的嵌套结构
    const actualData = response.data.data !== undefined ? response.data.data : response.data;
    console.log('食品收藏检查 - 实际data值:', actualData);
    console.log('食品收藏检查 - 判断结果:', actualData === 1 || actualData === true);
    
    // 根据API接口，返回值data: 0表示未收藏，1表示已收藏
    return actualData === 1 || actualData === true;
  } catch (error) {
    console.error('检查商品收藏状态失败:', error);
    return false;
  }
};

// 切换商品收藏状态
const toggleFoodFavorite = async () => {
  if (!selectedFood.value) return;
  
  try {
    if (isFoodFavorite.value) {
      await favoriteApi.removeFavoriteFood(selectedFood.value.id);
      ElMessage.success('已取消收藏');
    } else {
      await favoriteApi.addFavoriteFood(selectedFood.value.id);
      ElMessage.success('已收藏商品');
    }
    isFoodFavorite.value = !isFoodFavorite.value;
  } catch (error) {
    ElMessage.error('操作失败');
    console.error(error);
  }
};

// 加载商品评价
const loadFoodReviews = async (foodId: string) => {
  try {
    // 使用食品详情接口获取商品评价，评价包含在返回数据的 reviews 字段中
    const response = await foodApi.getFoodDetail(foodId);
    console.log('食品详情API响应:', response);
    
    if (response && response.data) {
      // 处理API响应数据结构
      let foodData = response.data as any;
      
      // 如果response.data是包装了一层的格式，提取实际数据
      if (foodData.data && typeof foodData.data === 'object') {
        foodData = foodData.data;
      }
      
      // 从食品详情中提取评价数据
      foodReviews.value = foodData.reviews || [];
      console.log('提取的食品评价:', foodReviews.value);
    } else {
      foodReviews.value = [];
    }
  } catch (error) {
    console.error('获取商品详情和评价失败:', error);
    foodReviews.value = [];
  }
};

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (days === 0) {
    return '今天';
  } else if (days === 1) {
    return '昨天';
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 按分类获取食品
const getFoodsByCategory = (categoryId: number) => {
  return foodsByCategory.value[categoryId] || [];
};

// 滚动到指定分类
const scrollToCategory = (categoryId: number | string) => {
  currentCategory.value = categoryId;
  let elementId = '';
  
  if (categoryId === 'featured') {
    elementId = 'category-featured';
  } else {
    elementId = `category-${categoryId}`;
  }
  
  const element = document.getElementById(elementId);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
};

// 处理标签页切换
const handleTabClick = (tab: any) => {
  if (tab.name === 'reviews' && reviews.value.length === 0) {
    loadReviews();
  }
};

// 打开食品详情
const openFoodDetail = async (food: Food) => {
  selectedFood.value = food;
  foodQuantity.value = 1;
  selectedAttributes.value = {};
  isFoodFavorite.value = false; // 重置收藏状态
  foodReviews.value = []; // 重置评价列表
  
  // 添加商品浏览历史
  try {
    await historyApi.addFoodHistory(food.id);
  } catch (error) {
    console.error('添加商品浏览历史失败:', error);
  }
  
  // 检查商品收藏状态
  const favoriteResult = await checkFoodFavorite(food.id.toString());
  console.log('设置食品收藏状态 - checkFoodFavorite返回值:', favoriteResult);
  isFoodFavorite.value = favoriteResult;
  console.log('设置食品收藏状态 - isFoodFavorite最终值:', isFoodFavorite.value);
  
  // 加载商品评价
  await loadFoodReviews(food.id.toString());
  
  // 初始化属性选择
  if (food.attributes && food.attributes.length > 0) {
    food.attributes.forEach(attr => {
      if (attr.multiSelect) {
        selectedAttributes.value[attr.name] = attr.options
          .filter(opt => opt.default)
          .map(opt => opt.name);
      } else {
        const defaultOption = attr.options.find(opt => opt.default);
        selectedAttributes.value[attr.name] = defaultOption ? defaultOption.name : attr.options[0].name;
      }
    });
  }
  
  foodDetailVisible.value = true;
};

// 添加商品到购物车
const addToCart = async (food: Food) => {
  try {
    // 简单版本：直接添加到购物车，无属性选择
    const response = await cartApi.addToCart({
      storeId: parseInt(storeId.value),
      foodId: food.id,
      quantity: 1
    });
    
    ElMessage.success('已加入购物车');
    await loadCartItems(); // 重新加载购物车
  } catch (error) {
    ElMessage.error('添加失败');
    console.error(error);
  }
};

// 添加选中的商品到购物车（带属性）
const addSelectedFoodToCart = async () => {
  if (!selectedFood.value) return;
  
  try {
    // 添加到购物车 - 注意：当前API不支持attributes，需要后端支持
    await cartApi.addToCart({
      storeId: parseInt(storeId.value),
      foodId: selectedFood.value.id,
      quantity: foodQuantity.value
    });
    
    ElMessage.success('已加入购物车');
    foodDetailVisible.value = false;
    await loadCartItems(); // 重新加载购物车
  } catch (error) {
    ElMessage.error('添加失败');
    console.error(error);
  }
};

// 更新购物车商品数量
const updateCartItemQuantity = async (item: CartItem, change: number) => {
  const newQuantity = item.quantity + change;
  
  console.log('更新购物车商品:', {
    itemId: item.id,
    foodName: item.foodName,
    currentQuantity: item.quantity,
    change,
    newQuantity
  });
  
  if (newQuantity <= 0) {
    // 如果数量变为0，则移除商品
    try {
      console.log('准备删除购物车项，ID:', item.id);
      await cartApi.removeFromCart(item.id);
      await loadCartItems(); // 重新加载购物车数据
    } catch (error) {
      ElMessage.error('移除失败');
      console.error('删除购物车项失败:', error);
    }
  } else {
    // 更新商品数量
    try {
      console.log('准备更新购物车项，ID:', item.id, '新数量:', newQuantity);
      await cartApi.updateCartItem(item.id, { quantity: newQuantity });
      await loadCartItems(); // 重新加载购物车数据，确保数据同步
    } catch (error) {
      ElMessage.error('更新失败');
      console.error('更新购物车项失败:', error);
    }
  }
};

// 清空购物车
const clearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await cartApi.clearStoreCart(parseInt(storeId.value));
    ElMessage.success('购物车已清空');
    cartItems.value = [];
    cartPanelVisible.value = false;
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败');
      console.error(error);
    }
  }
};

// 切换购物车面板显示
const toggleCartPanel = () => {
  if (cartItems.value.length > 0) {
    cartPanelVisible.value = !cartPanelVisible.value;
  } else {
    ElMessage.info('购物车是空的');
  }
};

// 前往结算页面
const goToCheckout = () => {
  if (getTotalPrice() < storeInfo.value.minOrder) {
    ElMessage.warning(`未达到起送价￥${storeInfo.value.minOrder}`);
    return;
  }
  
  // 确保购物车不为空
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，请先添加商品');
    return;
  }
  
  // 跳转到结算页面，传递店铺ID参数
  router.push({
    path: '/customer/checkout',
    query: {
      storeId: storeId.value
    }
  });
};

// 获取购物车总价
const getTotalPrice = () => {
  return cartItems.value.reduce((total, item) => total + item.price * item.quantity, 0);
};

// 获取购物车总数量
const getTotalItems = () => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0);
};

// 预览图片
const previewImage = (images: string[], index: number) => {
  // 格式化图片URL数组
  const formattedImages = images.map(img => formatImageUrl(img));
  
  // 简单的图片预览实现 - 在新窗口打开图片
  const imageUrl = formattedImages[index];
  if (imageUrl) {
    window.open(imageUrl, '_blank');
  }
  
  console.log('预览图片', formattedImages, index);
};
</script>

<style scoped>
.store-detail-container {
  width: 100%;
  max-width: 95%;
  margin: 0 auto;
  padding-bottom: 60px; /* 为购物车栏留出空间 */
  min-width: 320px;
}

/* 顶部区域（商家概览） */
.store-header {
  width: 100%;
  position: relative;
}

.store-cover {
  width: 100%;
  height: 200px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.store-info-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  color: white;
  display: flex;
  align-items: flex-end;
}

.store-logo {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 15px;
  border: 2px solid white;
}

.store-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.store-basic-info {
  flex: 1;
}

.store-name {
  font-size: 24px;
  margin: 0 0 5px;
}

.store-stats {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.divider {
  margin: 0 8px;
  color: rgba(255, 255, 255, 0.6);
}

.store-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.store-actions {
  margin-left: 15px;
}

/* 导航区域 */
.nav-container {
  background: white;
  z-index: 10;
}

.nav-container.sticky {
  position: sticky;
  top: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 点菜区域 */
.menu-container {
  margin-top: 20px;
}

.menu-layout {
  display: flex;
  gap: 20px;
}

.category-nav {
  width: 180px;
  position: sticky;
  top: 60px;
  align-self: flex-start;
  max-height: calc(100vh - 60px);
  overflow-y: auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: width 0.3s ease;
}

.category-nav.collapsed {
  width: 60px;
}

.category-nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
  border-radius: 8px 8px 0 0;
}

.category-nav.collapsed .category-nav-header {
  padding: 12px 8px;
  justify-content: center;
}

.nav-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.toggle-btn {
  padding: 4px !important;
  min-height: auto !important;
}

.category-nav ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.category-nav li {
  padding: 12px 15px;
  cursor: pointer;
  border-left: 3px solid transparent;
  display: flex;
  align-items: center;
  white-space: nowrap;
  overflow: hidden;
  transition: all 0.2s ease;
}

.category-nav.collapsed li {
  padding: 12px 8px;
  justify-content: center;
}

.category-nav li:hover {
  background: #f8f9fa;
}

.category-nav li.active {
  color: #409EFF;
  background: #f0f9ff;
  border-left-color: #409EFF;
}

.category-icon {
  margin-right: 8px;
  font-size: 16px;
  min-width: 16px;
  text-align: center;
}

.category-nav.collapsed .category-icon {
  margin-right: 0;
}

.category-text {
  flex: 1;
  transition: opacity 0.2s ease;
}

.category-nav.collapsed .category-text {
  opacity: 0;
  width: 0;
  overflow: hidden;
}

.food-list {
  flex: 1;
}

.category-section {
  margin-bottom: 30px;
}

.category-title {
  font-size: 18px;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.featured-title {
  color: #ff6600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.featured-title .el-icon {
  color: #ff9900;
}

.foods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

/* 评价区域 */
.reviews-container {
  margin-top: 20px;
}

.reviews-summary {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.overall-rating {
  text-align: center;
  padding-right: 20px;
  border-right: 1px solid #eee;
  margin-right: 20px;
}

.overall-rating h3 {
  font-size: 32px;
  color: #ff9900;
  margin: 0;
}

.rating-filters {
  flex: 1;
}

.reviews-list {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 商家详情区域 */
.store-detail-info {
  margin-top: 20px;
}

.store-map {
  margin-top: 20px;
  height: 300px;
  background: #f5f5f5;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 底部购物车区域 */
.cart-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  padding: 0 20px;
  z-index: 100;
}

.cart-info {
  flex: 1;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.cart-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  margin-right: 15px;
  position: relative;
}

.cart-icon.has-items {
  background: #409EFF;
  color: white;
}

.cart-count {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #ff4d4f;
  color: white;
  font-size: 12px;
  min-width: 20px;
  height: 20px;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 5px;
}

.total-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff6600;
}

.min-price-tip {
  margin-left: 10px;
  font-size: 14px;
  color: #999;
}

.empty-cart {
  color: #999;
}

.checkout-btn {
  margin-left: 15px;
}

/* 购物车面板 */
.cart-panel-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-cart-tip {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
}

.empty-cart-tip .el-icon {
  margin-bottom: 15px;
}

.cart-item-list {
  flex: 1;
  overflow-y: auto;
}

.cart-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.item-info {
  display: flex;
  flex: 1;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 10px;
}

.item-details {
  flex: 1;
}

.item-details h4 {
  margin: 0 0 5px;
  font-size: 16px;
}

.item-details p {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.item-price-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
}

.item-price {
  font-weight: bold;
  color: #ff6600;
}

.item-quantity {
  display: flex;
  align-items: center;
}

.quantity {
  margin: 0 10px;
  min-width: 20px;
  text-align: center;
}

.cart-summary {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  font-weight: bold;
  font-size: 18px;
}

.cart-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

/* 商品详情弹窗 */
.food-detail-content {
  display: flex;
  gap: 30px;
}

.food-detail-left {
  flex-shrink: 0;
}

.food-detail-image {
  width: 250px;
  height: 250px;
  border-radius: 8px;
  overflow: hidden;
}

.food-detail-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.food-detail-right {
  flex: 1;
  min-width: 0;
}

.food-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.food-detail-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.favorite-btn {
  flex-shrink: 0;
}

.food-detail-desc {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.4;
}

.food-detail-price {
  margin-bottom: 10px;
}

.current-price {
  font-size: 20px;
  color: #ff6600;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.food-detail-stats {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #666;
}

.food-attributes {
  margin: 20px 0;
}

.attr-group {
  margin-bottom: 15px;
}

.attr-group h4 {
  margin-bottom: 10px;
}

.required {
  color: #f56c6c;
  margin-left: 5px;
}

.optional {
  color: #999;
  margin-left: 5px;
  font-size: 12px;
  font-weight: normal;
}

.attr-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.option-price {
  margin-left: 5px;
  color: #ff6600;
  font-size: 12px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 20px 0;
  padding: 15px 0;
  border-top: 1px solid #eee;
}

.quantity-controls {
  display: flex;
  align-items: center;
}

.quantity {
  margin: 0 15px;
  min-width: 30px;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

/* 商品评价样式 */
.food-reviews-section {
  margin-top: 25px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.food-reviews-section h3 {
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.food-reviews-list {
  max-height: 300px;
  overflow-y: auto;
}

.food-review-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.food-review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.review-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.review-content {
  margin: 8px 0;
  font-size: 14px;
  line-height: 1.4;
  color: #666;
}

.review-images {
  display: flex;
  gap: 8px;
  margin-top: 10px;
}

.review-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.2s;
}

.review-image:hover {
  transform: scale(1.05);
}

.no-reviews {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

@media (max-width: 768px) {
  .menu-layout {
    flex-direction: column;
  }
  
  .category-nav {
    width: 100% !important;
    position: static;
    display: flex;
    overflow-x: auto;
    white-space: nowrap;
    max-height: none;
    border-radius: 8px;
  }
  
  .category-nav-header {
    display: none;
  }
  
  .category-nav ul {
    display: flex;
    width: 100%;
  }
  
  .category-nav li {
    border-left: none;
    border-bottom: 3px solid transparent;
    min-width: fit-content;
    padding: 12px 16px;
  }
  
  .category-nav li.active {
    border-left-color: transparent;
    border-bottom-color: #409EFF;
  }
  
  .category-icon {
    margin-right: 4px;
  }
  
  .category-text {
    font-size: 14px;
  }
  
  .food-detail-content {
    flex-direction: column;
  }
  
  .food-detail-left {
    align-self: center;
  }
  
  .food-detail-image {
    width: 200px;
    height: 200px;
  }
  
  .food-reviews-list {
    max-height: 200px;
  }
}
</style>
